import log from '../../../helpers/logger';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
//import { validateLink } from '../../../helpers/dataValidation';

import {
  authorizedRouteHandler,
  ControllerMethodTypes,
  defaultRouteHandler,
} from '../../../../interfaces';
import { Request } from 'hyper-express';
import { showSelectedObjectKeys } from '../../../helpers/utilsJS';
import { minishop_sku } from '../../../../../prisma/generated/uctoo';
import { setExCache } from '../../../helpers/redis';
  //#region AutoCreateCode
import {
  createMinishopSku,
  deleteMinishopSkuFromDatabase,
  deleteMultiMinishopSkuFromDatabase,
  editMinishopSkuInDatabase,
  editMultiMinishopSkuInDatabase,
  getMinishopSkuFromDatabase,
  getMinishopSkusFromDatabase,
  queryMinishopSkusFromDatabase,
  countMinishopSkus
} from '../../../services/uctoo/minishop_sku';

class uctooMinishopSkuController {

  protected validateAndDestructureBody = async (
    req: Request,
    userId: string,
    actionType: ControllerMethodTypes
  ) => {
    const body = await req.json();
    const keysArray = Object.keys(body);       //如需自定义控制接收字段可在此定义，如['id','link','privacy_level','owner','description','group_id','stars'] ，默认接收所有提交字段
    const uctooMinishopSku = showSelectedObjectKeys(body, keysArray) as minishop_sku;
    uctooMinishopSku.creator = userId;

    return uctooMinishopSku;
  };
  public add: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const uctooMinishopSku = await this.validateAndDestructureBody(
        req,
        user,
        ControllerMethodTypes.ADD
      );
      if (!uctooMinishopSku) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

      const createdMinishopSku = await createMinishopSku(uctooMinishopSku);
      if (!createdMinishopSku) return res.status(500).json({ errno: "50001", errmsg: "database query failed" });

      res.status(200).json(createdMinishopSku);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public edit: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const body = await req.json();
      const { id,ids,force } = body;

      if(ids){
        const uctooMinishopSku = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooMinishopSku) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedMinishopSku = await editMultiMinishopSkuInDatabase(uctooMinishopSku, JSON.parse(ids), user);
        
        if (typeof editedMinishopSku === 'object' && 'success' in editedMinishopSku) {
          if (!editedMinishopSku.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: editedMinishopSku.reason,
              ...(editedMinishopSku.minishopSkuId && { minishopSkuId: editedMinishopSku.minishopSkuId })
            });
          }
          return res.status(200).json(editedMinishopSku.data);
        }
        
        res.status(200).json(editedMinishopSku);
      }else{
        const uctooMinishopSku = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooMinishopSku) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedMinishopSku = await editMinishopSkuInDatabase(uctooMinishopSku, uctooMinishopSku.id, user);
        
        if (typeof editedMinishopSku === 'object' && 'success' in editedMinishopSku) {
          if (!editedMinishopSku.success) {
            return res.status(403).json({ errno: "40301", errmsg: editedMinishopSku.reason });
          }
          return res.status(200).json(editedMinishopSku.data);
        }
        res.status(200).json(editedMinishopSku);
      }      
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public delete: authorizedRouteHandler = async (req, res) => {
    try {
      const body = await req.json();
      const { id,ids,force } = body;
      const user = res.locals.id.user;

      if(ids){
        const deletionResult = await deleteMultiMinishopSkuFromDatabase(JSON.parse(ids), force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: deletionResult.reason,
              ...(deletionResult.minishopSkuId && { minishopSkuId: deletionResult.minishopSkuId })
            });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }else{
        const deletionResult = await deleteMinishopSkuFromDatabase(id, force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({ errno: "40301", errmsg: deletionResult.reason });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }

      res.status(200).json({ desc: '删除成功' });
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getSingle: authorizedRouteHandler = async (req, res) => {
    try {
      const { id } = req.params;
      const user = res.locals.id.user;

      const minishopSkuFromDb = await getMinishopSkuFromDatabase(id, user);
      if (!minishopSkuFromDb) {
        return res.status(404).json({ 
          errno: "40401", 
          errmsg: '未找到该实体或您没有权限访问' 
        });
      }

      res.status(200).json(minishopSkuFromDb);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getMany: authorizedRouteHandler = async (req, res) => {
    try {
      const limit = parseInt(req.params.limit);
      const page = parseInt(req.params.page) || 0;
      const skip = parseInt(req.params.skip) || 0;
      const query = req.query;
      
      if (limit > 100) return res.status(400).json({ errno: "40002", errmsg: '请求数量不能超过100条' });
      if (isNaN(limit)) return res.status(400).json({ errno: "40003", errmsg: '请求数量必须是数字' });
      
      const user = res.locals.id.user;
      const totalCount = await countMinishopSkus(user);
      
      if (query) {
        const minishopSkusFromDb = await queryMinishopSkusFromDatabase(limit, page, skip, query, user);
        if (!minishopSkusFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount: totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          minishopSkus: minishopSkusFromDb
        });
      } else {
        const minishopSkusFromDb = await getMinishopSkusFromDatabase(limit, skip, page, user);
        if (!minishopSkusFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount:totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          minishopSkus: minishopSkusFromDb
        });
      }


    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  //#endregion AutoCreateCode
}

export default uctooMinishopSkuController;
